package com.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class AiUtil {


    public static String getAvUrl(String text, String m, String c, String r) throws Exception {
        Socket socket = null;
        try {
            socket = new Socket("e36ff7293101f071.natapp.cc", 12468);
            socket.setSoTimeout(10000);
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            JSONObject object = new JSONObject();
            object.put("model", m);
            object.put("config", c);
            object.put("index", r);
            String encode = Base64.encode(text.getBytes(StandardCharsets.UTF_8));
            object.put("text", encode);
            dos.writeUTF("#" + object.toJSONString());
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            byte[] bs = new byte[10240];
            int len = dis.read(bs);
            String str = new String(bs, 0, len);
            if (StrUtil.isNotBlank(str)) {
                return str;
            }
        } catch (IOException | NumberFormatException e) {
            e.printStackTrace();
        } finally {
            if(null != socket){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
